package cz.mff.kusad5am.hb.ws;

import java.util.List;

import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.xpath.XPath;
import org.springframework.ws.server.endpoint.AbstractJDomPayloadEndpoint;

import cz.mff.kusad5am.hb.schema.list.Hostel;
import cz.mff.kusad5am.hb.service.ListOfHostelsWorker;

public class ListOfHostelsEndpoint extends AbstractJDomPayloadEndpoint{
	private static final String myNs = "http://kusad5am.mff.cz/bs/schemas/list";
	
	private final ListOfHostelsWorker worker;
	
	
	public ListOfHostelsEndpoint(ListOfHostelsWorker worker) throws JDOMException {
		this.worker = worker;
	}

	
	@Override
	protected Element invokeInternal(Element arg0) throws Exception {
		Namespace ns = arg0.getNamespace();
		String nsp = ns.getPrefix();
		String country = XPath.newInstance("//"+nsp+":HostelListRequest/@Country").valueOf(arg0);
		String city = XPath.newInstance("//"+nsp+":HostelListRequest/@City").valueOf(arg0);
		String start = XPath.newInstance("//"+nsp+":HostelListRequest/@arrivalDate").valueOf(arg0);
		String guests = XPath.newInstance("//"+nsp+":HostelListRequest/@numberOfGuests").valueOf(arg0);
		String nights = XPath.newInstance("//"+nsp+":HostelListRequest/@numerOfNights").valueOf(arg0);
		
		List<Hostel> hostels = worker.getListOfHostels(country, city, null, 0, 0);
		Element response = createResponse(hostels, country, city, start, guests, nights, ns);
		return response;
	}
	
	
	
	private Element createResponse(List<Hostel> hostels, String country, String city, String start, String guests, String nights, Namespace tns) {
		Element response = new Element("HostelListResponse");
		response.setNamespace(tns);
		response.setAttribute("Country", country);
		response.setAttribute("City", city);
		response.setAttribute("arrivalDate", start);
		response.setAttribute("numberOfGuests", guests);
		response.setAttribute("numerOfNights", nights);
		for(Hostel h: hostels) {
			Element child = new Element("Hostel");
			child.setNamespace(tns);
			child.setAttribute("name", h.getName());
			child.setAttribute("id", new Integer(h.getId()).toString());
			child.setAttribute("priceDormFrom", h.getPriceDormFrom());
			child.setAttribute("pricePrivateFrom", h.getPricePrivateFrom());
			child.setAttribute("Country", h.getCountry());
			child.setAttribute("City", h.getCity());
			child.setAttribute("Address", h.getAddress());
			child.setAttribute("ZipCode", h.getZipCode());
			response.addContent(child);
		}
		
		return response;
	}
	
	
}